//
//  LYStatusPictureView.swift
//  微博
//
//  Created by liuerying on 16/5/26.
//  Copyright © 2016年 liuerying. All rights reserved.

//显示微博图片的视图

import UIKit
import SnapKit
import SDWebImage
private let ItemID = "ItemID"

private let pictureMargin: CGFloat = 3
//最大宽度
private let maxWidth = ScreeWidth - 2 * StatusCellMargin

//设置每一item的宽度
private let itemWidth = (maxWidth - 2 * pictureMargin) / 3

class LYStatusPictureView: UICollectionView {

    //数据源
    var pictures:[LYPicture]?{
    
        didSet{
        
            print(pictures?.count)
            let psize = calulatePictureViewSize()
            
            self.snp_updateConstraints(closure: { (make) in
                make.size.equalTo(psize)
                
            })
            //数据一旦改变就要刷新列表
            reloadData()
        }
        
        
    }
    

    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = pictureMargin
        layout.minimumInteritemSpacing = pictureMargin
        super.init(frame: frame, collectionViewLayout: layout)
        //设置代理
        self.delegate = self
        self.dataSource = self
        
    //设置不能相应点击状态栏快速回到的手势
    scrollsToTop = false
        
        //注册item
        registerClass(LYStatusPictureCell.self, forCellWithReuseIdentifier: ItemID)
  
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//    lazy var numLabel:UILabel=UILabel()
    
    
    func calulatePictureViewSize()-> CGSize {
    
        let imageCount = pictures?.count ?? 0
        
        if imageCount == 0{
        
            return CGSizeZero
        }
        
        //获取collectionView 的布局对象
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if imageCount == 1 {
        
            //TODO: 图片原比例显示
            let imageSize = CGSizeMake(100, 150)
            
            //给itmesize也要设置和图片大小一样
            layout.itemSize = imageSize
            return imageSize
        
        }
        
        //设置多张图片的itemSize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        if imageCount == 4{
        
            let w = itemWidth * 2 + pictureMargin
            return CGSizeMake(w, w)
      
        }
        /*
         1,2,3,
         4,5,6
         7,8,9

         因为count不是从1开始的,所以要先减1,在+1
         */
        
        //下面判断多张图片的时候
        
        let row = CGFloat((imageCount-1) / 3) + 1
        let maxHeight = row * itemWidth + (row-1) * pictureMargin
        
        return CGSizeMake(maxWidth, maxHeight)
    
    }
    

}


extension LYStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ItemID, forIndexPath: indexPath)as! LYStatusPictureCell
   
        //设置调试随机色
//        cell.backgroundColor = randomColor()
        cell.picture = pictures![indexPath.item]
    
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()

        browser.sourceImagesContainerView = self
        
        browser.imageCount = pictures?.count ?? 0
        
        browser.currentImageIndex = indexPath.item
        
        browser.delegate = self
        browser.show()
        
    }
 
}

//MARK: SDPhotoBrowser的代理方法
extension LYStatusPictureView: SDPhotoBrowserDelegate{

    //返回原来显示的小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        //获取点击的cell
        //返回cell的iconView的image
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = self.cellForItemAtIndexPath(indexPath)as! LYStatusPictureCell
        return cell.imageView.image
    }
    
    //返回的高清图图片的url地址
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        //获取缩略图的地址
        let urlStr = pictures![index].thumbnail_pic
        //修改地址中的thumbnail为bimiddle或者large
        let middleurString = urlStr?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
    
        let url = NSURL(string: middleurString!)
        
        return url
        
    }
    
}

class LYStatusPictureCell: UICollectionViewCell {

    var picture: LYPicture? {
    
        didSet{
            let url = NSURL(string: picture?.thumbnail_pic ?? "")
         
            imageView.sd_setImageWithURL(url)
       
            
        }
        
        
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置图片
   private func setupUI(){
    addSubview(imageView)
    
    //设置约束
    imageView.snp_makeConstraints { (make) in
        
        make.edges.equalTo(contentView.snp_edges)
    }
    
        
    }
    
    //懒加载控件
    lazy var imageView :UIImageView = {
    
        let img = UIImageView()
        
    
        //图片填充
        img.contentMode = .ScaleAspectFill
        
        img.clipsToBounds = true
       
        return img
        
    }()
}
